<?php
require_once dirname(dirname(__FILE__)).'/EOAuth2Service.php';
/**
 * StravaOAuthService class file.
 * 
 * @see http://developer.strava.com/healthgraph/registration-authorization
 */

/**
 * Strava provider class.
 * @package application.extensions.eauth.services
 */
class StravaOAuthService extends EOAuth2Service {	
	
	protected $name = 'strava';
	protected $title = 'Strava';
	protected $type = 'OAuth';
	protected $jsArguments = array('popup' => array('width' => 585, 'height' => 290));

	protected $client_id = '';
	protected $client_secret = '';
	protected $scope = 'write';
	protected $providerOptions = array(
		'authorize'		=> 'https://www.strava.com/oauth/authorize',
		'access_token'	=> 'https://www.strava.com/oauth/token',
	);

	protected function fetchAttributes() {
		$api = new Strava($this->getState('auth_token'));
		$info = $api->athlete();
		$this->attributes['id']		= $info->id;
		$this->attributes['name']	= trim($info->firstname.' '.$info->lastname);
		$this->attributes['avatar']	= $info->profile;
		$this->attributes['url']	= 'http://www.strava.com/athletes/'.$info->id;
	}
	
	protected function getCodeUrl($redirect_uri) {
		if (strpos($redirect_uri, '?') !== false) {
			$url = explode('?', $redirect_uri);
			$url[1] = preg_replace('#[/]#', '%2F', $url[1]);
			$redirect_uri = implode('?', $url);
		}
		$this->setState('redirect_uri', $redirect_uri);
		
		$url = parent::getCodeUrl($redirect_uri);
		if (isset($_GET['js'])) {
			$url .= '&display=popup';
		}
		return $url;
	}
	
	public function getState($key, $defaultValue = null) {
		return parent::getState($key, $defaultValue);
	}
	
	protected function getTokenUrl() {
		return $this->providerOptions['access_token'];
	}
	
	protected function getAccessToken($code) {
		$response = $this->makeRequest($this->getTokenUrl($code), array(
			'data' => array(
				'client_id'		=> $this->client_id,
				'client_secret' => $this->client_secret,
				'code'			=> $code,
			),
		), true);
		return $response;
	}
		
	/**
	 * Save access token to the session.
	 * @param array $token access token array.
	 */
	protected function saveAccessToken($token) {
		$this->setState('auth_token', $token->access_token);
		$this->setState('expires', isset($token->expires) ? time() + (int)$token->expires - 60 : 0);
		$this->access_token = $token->access_token;
	}
	
	/**
	 * Returns the error info from json.
	 * @param stdClass $json the json response.
	 * @return array the error array with 2 keys: code and message. Should be null if no errors.
	 */
	protected function fetchJsonError($json) {
		if (isset($json->error)) {
			return array(
				'code' => $json->error->code,
				'message' => $json->error->message,
			);
		}
		else {
			return null;
		}
	}		
}